<script setup lang="ts">
  import { ref, watch, nextTick } from 'vue';
  import { FormInstance, Message } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import { addSeal } from '@/api/seal';
  import Sigin from '../component/sigin.vue';
  import { adddoc } from '@/api/dashboard';
  const formRef = ref<FormInstance | null>(null);
  const props = defineProps({
    visible: Boolean,
    params: Object,
  });
  const siginImgUrl = ref<string>('');
  const { loading, setLoading } = useLoading();
  defineOptions({
    name: 'publifFileAdd',
  });

  // 基础表单配置（不含印章路径）
  const baseFormType = [
    {
      name: 'seal_name',
      label: '印章名称',
      type: 'a-input',
      fieldProps: {
        span: 24,
      },
      rules: [
        {
          message: '请输入',
          required: true,
        },
      ],
    },
    {
      name: 'seal_type',
      label: '印章类型',
      type: 'a-select',
      selectOptions: [
        {
          label: '印章',
          value: 1,
        },
        {
          label: '签名',
          value: 2,
        },
      ],
      fieldProps: {
        span: 24,
      },
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },
    {
      name: 'seal_state',
      label: '印章状态',
      type: 'a-select',
      slotName: 'status',
      selectOptions: [
        {
          status: 'success',
          value: 1,
          label: '启用',
        },
        {
          status: 'danger',
          value: 2,
          label: '禁用',
        },
      ],
      fieldProps: {
        span: 24,
      },
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },
  ];

  // 印章路径表单配置
  const sealPathFormItem = {
    label: '印章路径',
    name: 'doc_file',
    type: 'a-upload',
    fieldProps: {
      span: 24,
      action: 'global/upload',
      multiple: false,
      limit: 1,
      maxCount: 1,
      connectionName: 'doc_name',
    },
    rules: [
      {
        message: '请选择文件',
        required: true,
      },
    ],
  };

  // 最终表单配置 - 初始只包含基础表单
  const formType = ref([...baseFormType]);

  // 存储当前选择的印章类型
  const currentSealType = ref<number | undefined>(undefined);

  // 监听模态框可见性变化，重置表单状态
  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        // 模态框显示时重置表单
        currentSealType.value = undefined;
        formType.value = [...baseFormType];

        // 等待表单初始化完成后设置默认值
        nextTick(() => {
          // 设置默认值为第一个选项（如果存在）
          if (formRef.value && baseFormType[1].selectOptions?.length > 0) {
            formRef.value.setFormData({
              seal_type: baseFormType[1].selectOptions[0].value,
            });
          }
        });
      }
    }
  );

  // 监听印章类型变化
  watch(
    () => formRef.value?.formModel.seal_type,
    (newVal) => {
      currentSealType.value = newVal;

      // 根据印章类型动态更新表单配置
      if (newVal === 1) {
        // 类型为1时显示印章路径
        if (!formType.value.some((item) => item.name === 'doc_file')) {
          formType.value = [...baseFormType, sealPathFormItem];
        }
      } else {
        // 类型不为1时隐藏印章路径
        formType.value = baseFormType.filter(
          (item) => item.name !== 'doc_file'
        );
      }
    },
    { immediate: true } // 初始化时执行一次
  );
  const formData = ref({
    doc_file: '',
  });
  const emit = defineEmits(['update:visible', 'refresh']);

  const handleSubmit = async () => {
    if (!(await formRef.value?.checkForm())) {
      try {
        setLoading(true);
        // 根据当前表单类型决定是否包含印章路径
        const formModel = formRef.value?.formModel || {};
        const requestData = {
          seal_name: formModel.seal_name,
          seal_state: formModel.seal_state,
          seal_type: formModel.seal_type,
        };
        if (currentSealType.value === 1) {
          // 签章
          requestData['seal_path'] = formModel.doc_file?.[0]?.response?.[0];
        } else if (currentSealType.value === 2) {
          // 签名
          if (siginImgUrl.value) {
            requestData['seal_path'] = siginImgUrl.value;
          } else {
            Message.error('请签名后提交!');
            return false;
          }
        }
        const res = await addSeal(requestData);
        Message.success(res.msg);
        emit('update:visible', false);
        emit('refresh');
        setLoading(false);
      } catch (error) {
        setLoading(false);
      } finally {
        setLoading(false);
      }
    }
  };
</script>

<template>
  <a-modal
    title="添加印章"
    :visible="visible"
    @ok="handleSubmit"
    title-align="start"
    :ok-loading="loading"
    :width="650"
    @cancel="
      () => {
        emit('update:visible', false);
      }
    "
  >
    <pro-form
      ref="formRef"
      hiddenBtn
      :form-json="formType"
      :form-data="formData"
    ></pro-form>
    <Sigin v-model:imgUrl="siginImgUrl" v-if="currentSealType === 2" />
  </a-modal>
</template>

<style scoped lang="less">
  :deep(.arco-select-view-inner) {
    text-align: left !important;
  }
  .menu2 {
    height: 100%;
    box-sizing: border-box;
    padding: 10px;
    cursor: default !important;
    background: #f7f8fa;
  }
  :deep(.icon) {
    width: 1.2em !important;
    height: 1.2em !important;
  }

  :deep(.arco-tree-node-title-text) {
    font-size: 12px;
    width: 140px;
    overflow: hidden; /* 隐藏溢出内容 */
    white-space: nowrap; /* 禁止换行 */
    text-overflow: ellipsis; /* 显示省略号 */
  }

  :deep(.arco-tree-node-indent-block) {
    width: 0px !important;
  }

  :deep(.arco-tree-node-indent) {
  }
</style>
